package Dat05;

import java.io.*;
import java.util.Scanner;

public class Test02 {
    /**
     * 使用缓冲字节流复制myfile.txt文件为myfile_cp2.txt
     * @author Admin
     *
     */
    public static void main(String[] args) {
        File f = new File("src/dat03/myfile.txt");
        File f2 = new File("src/Dat05/myfile_cp2.txt");
        if(!f.exists()){
            try {
                f.createNewFile();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        if(!f2.exists()){
            try {
                f2.createNewFile();
                BufferedInputStream fin = new BufferedInputStream(new FileInputStream(f));
                // 修改：将FileOutputStream的第二个参数改为true，表示追加模式
                BufferedOutputStream fin1 = new BufferedOutputStream(new FileOutputStream(f,true));
                BufferedOutputStream fout = new BufferedOutputStream(new FileOutputStream(f2));

                Scanner in = new Scanner(System.in);
                System.out.println("请输入要复制的内容：");
                String str = in.nextLine();
                fin1.write(str.getBytes());
                fin1.flush(); // 确保数据写入文件
                System.out.println("写入成功");
                int len = -1;
                byte[] b = new byte[2048];
                while((len = fin.read(b)) != -1){
                    fout.write(b,0,len);
                }
                System.out.println("复制成功");
                fin.close();
                fin1.close();
                fout.close();

            }catch (Exception e){
                e.printStackTrace();
            }

        }
    }
}